package org.maxgroundstation.groundstation.comm.service.video;

import javax.swing.SwingUtilities;

import org.maxgroundstation.groundstation.comm.service.Service;
import org.maxgroundstation.groundstation.comm.service.ServiceCommunication;
import org.maxgroundstation.groundstation.comm.service.ServiceDataFrame;
import org.maxgroundstation.groundstation.comm.service.ServiceUtil;

/**
 * The video service.
 * @author Scott Davis
 * 
 * Copyright (C) 2010  Scott Davis
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class VideoService extends Service {

	// Static members
	public static final String SERVICE_BASE_ID = ServiceUtil.getServiceID("video");
	public static final String TYPE = "video";
	
	// Service event type
	public static final String VIDEO_IMAGE_DATA_RECEIVED = "video image data received";
	
	// Maximum time offset (milliseconds) before being considered old video frame data.
	private static final double MAX_TIME_OFFSET = 1000D;
	
	// Data members
	private String serviceID;
	private VideoRatePoller videoRatePoller;
	private byte[] lastVideoImageData;
	private double minTimeDiff = Double.POSITIVE_INFINITY;
	
	/**
	 * Constructor
	 * @param comm the service communication.
	 * @param serviceID the service ID;
	 */
	public VideoService(ServiceCommunication comm, String serviceID) {
		// Use Service constructor.
		super(comm);
		
		this.serviceID = serviceID;
		
		videoRatePoller = new VideoRatePoller();
	}
	
	@Override
	public String getID() {
		return serviceID;
	}
	
	@Override
	public boolean isSubscribable() {
		return true;
	}
	
	@Override
	public void initialize() {
		// Do nothing.
	}
	
	@Override
	public void handleResponse(ServiceDataFrame dataFrame) {
		
	    // Check if video frame is old.
	    double currentTime = (double) System.nanoTime() / 1000000D;
	    double dataFrameTime = (double) dataFrame.getTimestamp();
	    double timeDiff = currentTime - dataFrameTime;
	    if (timeDiff < minTimeDiff) {
	        minTimeDiff = timeDiff;
	        //System.out.println("New minTimeDiff: " + timeDiff);
	    }
	    //System.out.println("video dataframe timestamp: " + dataFrameTime + " currentTime: " + currentTime);
	    //System.out.println("timeDiff: " + timeDiff);
	    double timeOffset = timeDiff - minTimeDiff;
	    //System.out.println("timeOffset: " + timeOffset);
	    if (timeOffset > MAX_TIME_OFFSET) {
	        System.out.println("Video frame is over 1 sec old; discarding.");
	        return;
	    }
	    
		lastVideoImageData = dataFrame.getDataBytes();
		
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {

				// Add video frame received to video rate poller.
		        videoRatePoller.addFrameRecieved();
		        
		        fireServiceEvent(VIDEO_IMAGE_DATA_RECEIVED, lastVideoImageData);
			}
		});
	}

	@Override
	public boolean isDefaultService() {
		return false;
	}
	
	/**
	 * Gets the current video rate.
	 * @return video rate (FPS).
	 */
	public float getVideoRate() {
		return videoRatePoller.getVideoRate();
	}

    @Override
    public String getType() {
        return TYPE;
    }
}